package org.shopen.puremvc.view
{
	import mx.events.CloseEvent;
	import mx.managers.PopUpManager;
	
	import org.puremvc.as3.interfaces.INotification;
	import org.puremvc.as3.patterns.mediator.Mediator;
	import org.shopen.puremvc.ApplicationConstants;
	import org.shopen.puremvc.view.components.HelpWindow;

	public class HelpWindowMediator extends Mediator
	{
		public static const NAME : String = "HelpWindowMediator";
		
		protected var helpWindow : HelpWindow = null;
		
		public function HelpWindowMediator(viewComponent:Object=null)
		{
			super(HelpWindowMediator.NAME, viewComponent);
		}
		
		protected function get application() : Study
		{
			return viewComponent as Study;
		}
		
		override public function listNotificationInterests():Array
		{
			return [ApplicationConstants.SHOW_HELP];
		}
		
		override public function handleNotification(notification:INotification):void
		{
			switch(notification.getName())
			{
				case ApplicationConstants.SHOW_HELP:
					showHelpWindow();
					break;
			}
		}
		
		private function showHelpWindow() : void
		{
			// Make sure only one about window is shown
			if (helpWindow == null)
			{			
				helpWindow = createWindow();
				PopUpManager.addPopUp(helpWindow, application, false);
			}
			
			PopUpManager.bringToFront(helpWindow);
			PopUpManager.centerPopUp(helpWindow);
		}
		
		private function createWindow() : HelpWindow
		{
			var window : HelpWindow = new HelpWindow();
						
			window.addEventListener(CloseEvent.CLOSE, windowCloseListener);
			
			return window;
		}
		
		private function windowCloseListener(event : CloseEvent) : void
		{
			if (helpWindow == event.target)
			{
				helpWindow.removeEventListener(CloseEvent.CLOSE, windowCloseListener);
				PopUpManager.removePopUp(helpWindow);
				helpWindow = null;
			}
			else
			{
				sendNotification(ApplicationConstants.GENERAL_ERROR);
			}
		}
	}
}